import { Component, createRef } from 'react'
import classNames from 'classnames'
import { inject, observer } from 'mobx-react'

@inject('mainStore')
@observer
export default class TodoItem extends Component {
  state = {
    isEditing: false,
    currentName: '',
  }
  inputRef = createRef()
  handleDBlClick = () => {
    this.setState({ isEditing: !this.state.isEditing, currentName: this.props.item.name }, () => {
      this.inputRef.current.focus()
    })
  }
  handleBlur = () => {
    this.setState({ isEditing: false })
  }
  handleKeyUp = (e) => {
    if (e.key === 'Escape') {
      return this.setState({
        isEditing: false,
        currentName: '',
      })
    }
    if (e.key === 'Enter') {
      if (this.state.currentName.trim() === '') return alert('写点啥吧~')
      this.props.mainStore.updateTodo(this.props.item.id, 'name', this.state.currentName)
      this.setState({
        isEditing: false,
        currentName: '',
      })
    }
  }
  render() {
    const { isEditing, currentName } = this.state
    const { item } = this.props
    const { delTodo, updateTodo } = this.props.mainStore
    return (
      <li
        className={classNames({
          completed: item.done,
          editing: isEditing,
        })}
        key={item.id}
      >
        <div className='view'>
          <input className='toggle' type='checkbox' checked={item.done} onChange={() => updateTodo(item.id, 'done', !item.done)} />
          <label onDoubleClick={this.handleDBlClick}>{item.name}</label>
          <button className='destroy' onClick={() => delTodo(item.id)}></button>
        </div>
        <input className='edit' value={currentName} onChange={(e) => this.setState({ currentName: e.target.value })} ref={this.inputRef} onBlur={this.handleBlur} onKeyUp={this.handleKeyUp} />
      </li>
    )
  }
}
